package com.jelly.common.util.back;

import com.jelly.common.util.ListUtil;
import com.jelly.common.util.StringUtils;
import com.jelly.common.util.bean.SpringUtil;
import com.jelly.web.modules.system.permission.dao.PermissionAndRoleMapper;
import com.jelly.web.modules.system.permission.domain.PermissionAndRole;
import com.jelly.web.modules.system.permission.domain.PermissionAndRoleExample;
import com.jelly.web.modules.system.permission.service.IPermissionService;
import com.jelly.web.modules.system.role.domain.Role;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @创建人 ql
 * @创建时间 2018-09-10 15:00
 * @项目名称 jelly
 * @功能描述: 拦截更新
 **/
public class FilterChainDefinitionsUtil {

    public  static void updatePermission() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = SpringUtil.getBean(ShiroFilterFactoryBean.class);
        IPermissionService permissionService = SpringUtil.getBean(IPermissionService.class);
        synchronized (shiroFilterFactoryBean) {

            AbstractShiroFilter shiroFilter = null;
            try {
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean
                        .getObject();
            } catch (Exception e) {
                throw new RuntimeException(
                        "get ShiroFilter from shiroFilterFactoryBean error!");
            }

            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter
                    .getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver
                    .getFilterChainManager();

            // 清空老的权限控制
            manager.getFilterChains().clear();

            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
            //menuService.loadFilterChainDefinitions()
            /*查询权限角色信息 */
            shiroFilterFactoryBean.setFilterChainDefinitionMap(loadFilterChainDefinitions(permissionService.loadFilterChainDefinitions()));
            // 重新构建生成
            Map<String, String> chains = shiroFilterFactoryBean
                    .getFilterChainDefinitionMap();
            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim()
                        .replace(" ", "");
                manager.createChain(url, chainDefinition);
            }

        }

    }


    public static Map<String, String> loadFilterChainDefinitions(List<PermissionAndRole> list) {
        // 权限控制map.从数据库获取
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();

        //加载配置默认的过滤链
        filterChainDefinitionMap.put("/logout","logout");
        filterChainDefinitionMap.put("/login","anon,code");
        filterChainDefinitionMap.put("/css/**","anon");
        filterChainDefinitionMap.put("/smiditor/**","anon");
        filterChainDefinitionMap.put("/image/**","anon");
        filterChainDefinitionMap.put("/fonts/**","anon");
        filterChainDefinitionMap.put("/js/**","anon");
        filterChainDefinitionMap.put("/getGifCode","anon");
        filterChainDefinitionMap.put("/noAuthority.html","anon");

        //判断权限是否为空
        if(ListUtil.isNotList(list)){

            //循环拼接shiro所需的拦截详情进行返回
            for (PermissionAndRole permissionAndRole : list){

                //判断不为链接的权限信息
                if(!"jacascript:;".equals(permissionAndRole.getPerHref())){

                    //处理权限角色信息  进行拼接
                    String filterName = "";

                    //储存拼接后的角色
                    String roleRoute = "";

                    //获取菜单角色
                    List<Role> roleList = permissionAndRole.getRoleList();

                    //判断是否有角色
                    if(ListUtil.isNotList(roleList)){

                        //如果有则取出放入到shiro拦截规则中
                        for(Role role : roleList){
                            roleRoute += role.getRoleRoute()+",";
                        }

                    }

                    //判断拼接后的角色不能为空
                    if(StringUtils.isNotBlank(roleRoute)){

                        //去除最后一位‘.’号
                        roleRoute = roleRoute.substring(0,roleRoute.length() - 1);

                        filterName+="role["+roleRoute+"],";

                    }

                    if(StringUtils.isNotBlank(permissionAndRole.getPerRoute())) {

                        filterName += "permission[" + permissionAndRole.getPerRoute() + "]";
                    }else
                        //判断拼接后的拦截条件是否为空
                        if (StringUtils.isNotBlank(filterName)){

                            //权限为空则去除角色拼接最后一位‘.’号
                            filterName = filterName.substring(0,filterName.length() - 1);
                        }

                    filterChainDefinitionMap.put(permissionAndRole.getPerHref(),filterName);

                }

            }

        }

        filterChainDefinitionMap.put("/admin/**/**/update","testFilter");
        filterChainDefinitionMap.put("/admin/**/**/delect","testFilter");
        filterChainDefinitionMap.put("/admin/**/**/delects","testFilter");
        filterChainDefinitionMap.put("/admin/**/**/add","testFilter");
        filterChainDefinitionMap.put("/share/**/update","testFilter");
        filterChainDefinitionMap.put("/**","authc,remUrlId,kickout,userFilter");

        return filterChainDefinitionMap;
    }

}
